<?php
namespace App\Http\Controllers\SysAdmin;

use App\Models\Attendance;
use App\Models\Company;
use App\Models\Message;
use App\Models\RewardPunishDetail;
use App\Models\RewardPunishDetailLog;
use App\Models\RewardPunishSet;
use App\Models\ShenpiDetail;
use App\Models\ShenpiDetailLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Models\User;
use App\Models\RoleUser;


class RewardController extends BaseController
{
    protected $corpid;
    protected $user;
    protected $role;


    public function __construct() {
        parent::__construct();
        $this->role = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9','12'])->get();
        if(count($this->role) == 0){
            abort(403,'您没有权限访问该页面');
        }
    }
    



    //奖惩等级及分值
    public function getRewardPunishSet(Request $request)
    {
        $admin = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9'])->get();
        if(empty($admin)){
            abort(403,'需要系统管理员权限');
        }

        $year_param = $request->input('year', 0);
        $company = Company::where('id',$this->corpid)->first();
        if(!is_positive_int($year_param)){
            $year_param = getCurrentYear();
        }
        if(!in_array($year_param,explode(',',$company->years_array))){
            $year_param = $company->from_year;
        }

        $years = explode(',',$company->years_array);
        rsort($years);
        $now = date('Y') + 10;
        $yearlist = array();
        foreach($years as $y){
            $yearlist[] = array(
                'id'=>$y,
                'value'=>$y.'年',
            );
        }
        $yearlist = json_encode($yearlist);

        $default = array(
            '高级'=>'5',
            '中级'=>'3',
            '低级'=>'1',
        );
        $reward_exist = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->corpid)->where('kind','1')->first();
        $punish_exist = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->corpid)->where('kind','2')->first();
        if(empty($reward_exist)){
            $reward = new RewardPunishSet();
            $reward->kind = 1;
            $reward->corpid = $this->corpid;
            $reward->detail = serialize($default);
            $reward->save();
            $reward_exist = $reward;
        }
        if(empty($punish_exist)){
            $punish = new RewardPunishSet();
            $punish->kind = 2;
            $punish->corpid = $this->corpid;
            $punish->detail = serialize($default);
            $punish->save();
            $punish_exist = $punish;

        }
        if($punish_exist->corpid != $this->corpid || $reward_exist->corpid != $this->corpid){
            return '您没有权限查看该意见项';
        }

        $view = 'sysadmin.rewards-setting';
        return view($view)
            ->with('year_param', $year_param)
            ->with('yearlist', $yearlist)
            ->with('reward',$reward_exist)
            ->with('punish',$punish_exist);
    }


    //修改意见项等级及分值
    public function postModifyRewardSet(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $year_param = $request->input('year', 0);
        $company = Company::where('id',$this->corpid)->first();
        if(!is_positive_int($year_param)){
            $year_param = getCurrentYear();
        }
        if(!in_array($year_param,explode(',',$company->years_array))){
            $year_param = $company->from_year;
        }
        
        $reward = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->corpid)->where('kind','1')->first();
        $punish = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->corpid)->where('kind','2')->first();
        if(empty($reward) || empty($punish)){
            $result['status'] = 'fail';
            $result['msg'] = '奖惩不存在';
            return Response::json($result);
        }

        //奖励等级分值
        $reward_name = $request->input('reward_name');
        if(empty($reward_name)){
            $reward_name = array('高级','中级','低级');
        }else{
            $reward_name = json_decode($reward_name);
        }
        $reward_score = $request->input('reward_score');
        $reward_score = json_decode($reward_score);

        $reward_array = array();
        foreach ($reward_name as $k=>$v){
            if(empty($v) || !isset($reward_score[$k])){
                $result['status'] = 'fail';
                $result['msg'] = '等级名称或分值不能为空';
                return Response::json($result);
            }
            $reward_array[trim($v)] = intval(trim($reward_score[$k]));
        }
        $reward->detail = serialize($reward_array);
        $reward->save();

        //惩罚等级分值
        $punish_name = $request->input('punish_name');
        if(empty($punish_name)){
            $punish_name = array('高级','中级','低级');
        }else{
            $punish_name = json_decode($punish_name);
        }
        $punish_score = $request->input('punish_score');
        $punish_score = json_decode($punish_score);
        $punish_array = array();
        foreach ($punish_name as $k=>$v){
            if(empty($v) || !isset($punish_score[$k])){
                $result['status'] = 'fail';
                $result['msg'] = '等级名称或分值不能为空';
                return Response::json($result);
            }
            $punish_array[trim($v)] = intval(trim($punish_score[$k]));
        }
        $punish->detail = serialize($punish_array);
        $punish->save();

        $result['msg'] = '奖惩等级分值保存成功';
        return Response::json($result);
    }
    
    
    //奖惩管理员可以审核的奖惩列表
    public function getRewardlist()
    {
        $admin = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9'])->get();
        if(count($admin)==0){
            $is_big = 0;
            $jc = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->where('role_id','12')->first();
            $jc_scope = unserialize($jc->scope);
            $reward = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->whereIn('to_user_id',$jc_scope)->where('is_effective','0')->orderBy('created_at','desc')->get();
            $reward2 = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->whereIn('to_user_id',$jc_scope)->whereIn('is_effective',[1,2])->orderBy('created_at','desc')->get();
            foreach ($reward2 as $r){
                $reward[] = $r;
            }
            $punish = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->whereIn('to_user_id',$jc_scope)->where('is_effective','0')->orderBy('created_at','desc')->get();
            $punish2 = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->whereIn('to_user_id',$jc_scope)->whereIn('is_effective',[1,2])->orderBy('created_at','desc')->get();
            foreach ($punish2 as $p){
                $punish[] = $p;
            }
            $pcount = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->whereIn('to_user_id',$jc_scope)->where('is_effective','0')->count();
            $rcount = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->whereIn('to_user_id',$jc_scope)->where('is_effective','0')->count();
            $shenpicount = ShenpiDetail::where('corpid',$this->corpid)->whereIn('from_user_id',$jc_scope)->where('status','0')->count();
            
            //$view = 'sysadmin.reward-admin';//老的
            $view = 'sysadmin.verify-reward';

        }else{
            $is_big = 1;
            $shenpicount = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->count();
            $pcount = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->where('is_effective','0')->count();
            $rcount = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->where('is_effective','0')->count();
            $reward = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->where('is_effective','0')->orderBy('created_at','desc')->get();
            $reward2 = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->whereIn('is_effective',[1,2])->orderBy('created_at','desc')->get();
            foreach ($reward2 as $r){
                $reward[] = $r;
            }
            $punish = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->where('is_effective','0')->orderBy('created_at','desc')->get();
            $punish2 = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->whereIn('is_effective',[1,2])->orderBy('created_at','desc')->get();
            foreach ($punish2 as $p){
                $punish[] = $p;
            }
            //$view = 'sysadmin.rewards-punish';//原版
            $view = 'sysadmin.verify-reward';

        }
        $reward_set = RewardPunishSet::where('corpid',$this->corpid)->where('kind','1')->first();
        $punish_set = RewardPunishSet::where('corpid',$this->corpid)->where('kind','2')->first();
        $reward_set = unserialize($reward_set->detail);
        foreach ($reward_set as $k=>$v){
            $setR[] = array(
                'title'=>$k,
                'value'=>$v
            );
        }
        $punish_set = unserialize($punish_set->detail);
        foreach ($punish_set as $k=>$v){
            $setP[] = array(
                'title'=>$k,
                'value'=>$v
            );
        }
        $setR = json_encode($setR);
        $setP = json_encode($setP);
        
        return view($view)
            ->with('is_big',$is_big)
            ->with('shenpicount',$shenpicount)
            ->with('pcount',$pcount)
            ->with('rcount',$rcount)
            ->with('reward_set',$setR)
            ->with('punish_set',$setP)
            ->with('reward',$reward)
            ->with('punish',$punish);
    }


    //管理员审批待办事项
    public function getVerifyShenpi(Request $request)
    {
        $admin = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->whereIn('role_id',['9'])->get();
        if(count($admin)==0){
            $is_big = 0;
            $jc = RoleUser::where('user_id',$this->user->id)->where('corpid',$this->corpid)->where('role_id','12')->first();
            $jc_scope = unserialize($jc->scope);
            $shenpicount = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->where('is_notify',0)->whereIn('from_user_id',$jc_scope)->count();
            $rcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->whereIn('from_user_id',$jc_scope)->where('kind','1')->count();
            $pcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->whereIn('from_user_id',$jc_scope)->where('kind','2')->count();
            $shenpi = ShenpiDetail::where('corpid',$this->corpid)->where('is_notify',0)->whereIn('from_user_id',$jc_scope)->orderBy('status','asc')->orderBy('created_at','desc')->get();

            //$view = 'sysadmin.reward-admin';
        }else{
            $is_big = 1;
            $shenpicount = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->where('is_notify',0)->count();
            $rcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('kind','1')->count();
            $pcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('kind','2')->count();
            $shenpi = ShenpiDetail::where('corpid',$this->corpid)->where('is_notify',0)->orderBy('status','asc')->orderBy('created_at','desc')->get();

            //$view = 'sysadmin.reward-admin';
        }
        


        $kind_array = array('出差','事假','病假','年假','婚假','其他');

        $view = 'sysadmin.verify-reward1';

        return view($view)
            ->with('is_big',$is_big)
            ->with('shenpicount',$shenpicount)
            ->with('kind_array',$kind_array)
            ->with('pcount',$pcount)
            ->with('rcount',$rcount)
            ->with('shenpi',$shenpi);
    }



    //奖惩管理员审核的奖惩
    public function postVerifyReward(Request $request)
    {
        $response = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        
        $rewardid = $request->input('rid',0);
        $grade = $request->input('grade','');
        $is_agree = $request->input('agree','1');
        $score = $request->input('level',0);
        $reason = $request->input('reason','');
        if($is_agree == '1'){
            if( empty($grade) ||  $rewardid<=0){
                $result['msg'] = '参数有误';
                return Response::json($result);
            }
        }else{
            if($rewardid<=0){
                $result['msg'] = 'id参数有误';
                return Response::json($result);
            }
        }

        $reward = RewardPunishDetail::find($rewardid);
        if(empty($reward)){
            $response['msg'] = '该记录不存在';
            return Response::json($response);
        }

        if($reward->corpid != $this->corpid){
            $response['msg'] = '您没有权限审核该项目';
            return Response::json($response);
        }
        
        $detail = unserialize($reward->detail);
        if($is_agree != '1'){
            if(empty($reason)){
                $msg = getUserName($this->user->id).'不同意该奖惩记录';
            }else{
                $msg = getUserName($this->user->id).'不同意该奖惩记录,拒绝理由:'.$reason;
            }

            $reward->effective_month = date('Ym',time());
            $reward->is_effective = 2;
            $method = 2;
        }else{
            $msg = getUserName($this->user->id).'同意该奖惩记录，等级为'.$grade;
            $reward->is_effective = 1;
            $reward->effective_month = date('Ym',time());
            if($reward->grade == $grade){
                $method = 1;//同意
            }else{
                $reward->grade = $grade;
                $method = 3;//修改等级
            }
            $reward->score = $score;
        }
        $detail[] = $msg;
        $detail[] = '奖惩生效';
        $reward->detail = serialize($detail);
        $reward->final_user_id = $this->user->id;
        $reward->save();

        $delete_log = RewardPunishDetailLog::where('rp_id',$reward->id)->where('method',4)->delete();
        
        $log = new RewardPunishDetailLog();
        $log->rp_id = $reward->id;
        $log->operater_id = $this->user->id;
        $log->group_id = 0;
        $log->des = $msg;
        $log->method = $method;
        $log->save();

        $log1 = new RewardPunishDetailLog();
        $log1->rp_id = $reward->id;
        $log1->operater_id = $this->user->id;
        $log1->group_id = 0;
        $log1->des = '奖惩生效';
        $log1->method = $method;
        $log1->save();
        
        //生效时发送系统消息
        $message = new Message();
        $message->corpid = $this->corpid;
        $message->kind = $reward->kind;
        if($reward->kind=='1'){
            $scope = '';
            $kname = '奖励';
        }else{
            $kname = '惩罚';
            $arr = array($reward->from_user_id,$reward->to_user_id);
            $scope = serialize($arr);
        }
        $message->content = getUserName($reward->from_user_id).'发起的对'.getUserName($reward->to_user_id).'的'.$kname.'已生效';
        $message->scope = $scope;
        $message->save();
        

        $response['status'] = 'success';
        $response['msg'] = '审核奖惩成功';
        return Response::json($response);
    }



    //管理员审核奖励或惩罚
    public function postVerifyShenpi(Request $request)
    {
        $response = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );

        $rewardid = $request->input('rid',0);
        $is_agree = $request->input('agree','1');
        //dd($request->all());
        if($is_agree == 1){
            if($rewardid<=0){
                $result['msg'] = '通过参数有误';
                return Response::json($result);
            }
        }else{
            if($rewardid<=0){
                $result['msg'] = '拒绝参数有误';
                return Response::json($result);
            }
        }

        $reward = ShenpiDetail::where('is_notify',0)->find($rewardid);
        if(empty($reward)){
            $response['msg'] = '该记录不存在或无需审批';
            return Response::json($response);
        }
        $up_group_id = 0;
        $detail = unserialize($reward->detail);
        if($is_agree != '1'){
            if(empty($reason)){
                $msg = '管理员'.$this->user->qw_name.'不同意该申请';
            }else{
                $msg = '管理员'.$this->user->qw_name.'不同意该申请';
            }
        }else{
            $msg = '管理员'.$this->user->qw_name.'同意该申请';
        }
        $detail[] = $msg;
        if($is_agree == '1'){
            $method = 1;//同意
            $reward->status = 1;

            $time = strtotime($reward->date_param);
            $Attendance=Attendance::firstOrCreate(['time'=>$time,'corpid'=>$this->corpid,'user_id'=>$reward->from_user_id]);
            $data['year_param'] = date('Y',$time);
            $data['month_param'] = date('Ym',$time);
            $data['date_param'] = date('Ymd',$time);
            $Attendance->update($data);
            if($reward->kind == 1){
                $Attendance->chuchai = 1;
            }elseif ($reward->kind == 2){
                $Attendance->business = 1;
            }elseif ($reward->kind == 3){
                $Attendance->sick = 1;
            }
            elseif ($reward->kind == 4){
                $Attendance->public = 1;//年假
            }elseif ($reward->kind == 5){
                $Attendance->public = 2;//婚假
            }
            elseif ($reward->kind == 6){
                $Attendance->qita = 1;
            }
            $Attendance->save();
        }else{
            $method = 2;
            $reward->status = 2;
        }
        //$reward->current_group_id = $reward->current_group_id;
        $reward->detail = serialize($detail);
        if($up_group_id == '0'){
            $reward->effective_month = date('Ym',time());
            $detail[] = '申请生效';
        }
        $reward->save();

        $log = new ShenpiDetailLog();
        $log->rp_id = $reward->id;
        $log->operater_id = $this->user->id;
        $log->des = $msg;
        $log->group_id = -1;
        $log->method = $method;
        $log->save();

        $delete_log = ShenpiDetailLog::where('rp_id',$reward->id)->where('method',4)->delete();


        $response['status'] = 'success';
        $response['msg'] = '审核成功';
        return Response::json($response);

    }



   
}


